﻿using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Medianamik.Core;
using Medianamik.Core.Sugar;

namespace Medianamik.UI.Controls
{
    public class DocumentUploader : BaseMedianamikControl
    {
        private readonly Literal _documentLiteral = new Literal { ID = "DocumentTitleField" };
        private readonly HiddenField _hidden = new HiddenField { ID = ControlToValidateId };
        private readonly Image _openWindowButton = new Image { ID = "OpenWindowButton" };
        private readonly ImageButton _deleteButton = new ImageButton { ID = "DeleteButton" };

        public DocumentUploader()
        {
            IsMultiLingual = false;
        }

        protected override void CreateControlHierarchy(bool pUseDataSource)
        {
            Controls.Add(_documentLiteral);
            Controls.Add(_openWindowButton);
            Controls.Add(new LiteralControl("&nbsp;"));
            Controls.Add(_deleteButton);
            Controls.Add(_hidden);

            _deleteButton.Click += DeleteDocument;

            if (pUseDataSource)
            {
                _openWindowButton.ImageUrl = "/medianamik/images/icones/ico_repertoire.gif";
                _openWindowButton.CssClass = "IconePathPicker";

                _deleteButton.ImageUrl = "/medianamik/images/Icones/Ico_Supprimer.gif";
                _deleteButton.CssClass = "IconePathPicker";
                _deleteButton.Attributes.Add("onclick", "return confirm('Êtes-vous certain de vouloir supprimer ce document?');");

                SetValue(DataSource);
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            if (!Page.ClientScript.IsClientScriptBlockRegistered(GetType(), ClientID + "DocumentUploaderJS"))
            {
                var js = Resources.GetResourceText("Scripts.DocumentUploader.js", GetType().Assembly);

                if (!string.IsNullOrEmpty(js))
                {
                    ScriptManager.RegisterStartupScript(this, GetType(), ClientID + "DocumentUploaderJS",
                        String.Format(js, ClientID + "documentTitleField", _hidden.ClientID, ClientID), true);
                }
            }

            base.OnPreRender(e);
        }

        void DeleteDocument(object sender, ImageClickEventArgs e)
        {
            if (_hidden.Value.Length > 0)
            {
                Guid nodeId;
                if (_hidden.Value.IsGuidInline(out nodeId))
                {
                    NodeManager.DestroyNode(nodeId);
                }
            }

            //TODO: JavaScript Confirm
            _hidden.Value = "";
            SetDocumentTitleFieldToDefaultValue();
        }

        private void SetDocumentTitleFieldToDefaultValue()
        {
            _documentLiteral.Text = "<span id=\"" + ClientID + "documentTitleField\">Aucun document</span>&nbsp;&nbsp;";
        }

        public override void SetValue(object value)
        {
            EnsureChildControls();
            string strNodeId;

            if (value == null)
            {
                _hidden.Value = "";
                SetDocumentTitleFieldToDefaultValue();
                strNodeId = Guid.NewGuid().ToString();
            }
            else
            {
                strNodeId = value.ToString();
                _hidden.Value = strNodeId;
                var node = NodeManager.GetNode((Guid)value);

                if (node != null)
                {
                    _documentLiteral.Text = String.Format("<span id=\"" + ClientID + "documentTitleField\"><a  target=\"_blank\" href=\"{0}\">{1}</a></span>&nbsp;&nbsp;",
                       HttpContext.Current.Server.PhysicalPathToRelativePath(node["fr-ca"]["PhysicalPath"].Value.ToString()), node["fr-ca"]["Name"].Value);
                }
                else
                {
                    SetDocumentTitleFieldToDefaultValue();
                }
            }

            _openWindowButton.Attributes.Add("onclick", String.Format("showTelerikWindow('DocumentUploaderWindow','','/medianamik/modalwindows/DocumentUploaderWindow.aspx?id={0}', onClientClose" + ClientID + ");return false;",
                strNodeId));
        }

        public override Type TypeOfValue
        {
            get { return typeof(Guid?); }
        }

        public override object GetValue()
        {
            EnsureChildControls();

            Guid? result = null;
            return _hidden.Value.IsGuidInline(ref result) ? result : default(Guid?);
        }
    }
}